import axios from 'axios'
import {Message} from 'element-ui'
// axios 配置
axios.defaults.timeout = 3000;
axios.defaults.withCredentials = true;
if (process.env.NODE_ENV === "dev") {
  axios.defaults.baseURL = "http://127.0.0.1:7001"
}


axios.interceptors.request.use(config => {
    config.headers = {
      'Content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
    };
    const data = config.data;
    if (!data) {
      return config;
    }
    const key = Object.keys(data);
    config.data = encodeURI(key.map(name => `${name = $data[name]}`).join('&'));
    return config;

  },
  error => {
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(response => {
    const res = response.data;
    if (res.code !== 200) {
      Message({
        message: res.message,
        type: 'error',
        duration: 5 * 1000
      });
    } else {
      return response.data
    }
  }, error => {
    console.log("error:", error);
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);

export default axios;
